<template>
    <div>

        <el-switch 
            v-model="draggable"
            active-text="开启拖拽"
            inactive-text="关闭拖拽"
            >
        </el-switch>


        <el-button @click="batchSave" v-if="draggable">批量保存</el-button>
        <el-button @click="batchDelete" type="danger">批量删除</el-button>
        

      <el-tree
        ref="menuTree"
        :data="data"
        :props="defaultProps"
        show-checkbox
        @node-click="handleNodeClick"
        @node-drop="handleDrop"
        node-key="catId"
        highlight-current
        accordion
        :default-expanded-keys="expandedKey"
        :draggable="draggable"
        :allow-drop="allowDrop"
      >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
            <el-button 
            v-if="node.level != 2"
            type="text"
            size="mini"
            @click="() => append(data)"            
            >

            Append
            </el-button>


            <el-button 
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node,data)"            
            >

            Delete
            </el-button>

            <el-button type="text" size="mini" @click="() => edit(data)">
                    Edit
            </el-button>
        </span>
      </span>
      </el-tree>

      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form :model="category">

        
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumitData">确 定</el-button>
      </span>
    </el-dialog>




    </div>
  </template>
  
  <script>
import { id } from 'html-webpack-plugin/lib/chunksorter';

  export default {
    //import 引入的组件需要注入到对象中才能使用
    components:{},
    props:{},
    props:{},

    data() {
      return {
        pCid:[],
        draggable:false,
        updateNodes:[],
        maxLevel:0,
        dialogType: "", //edit,add
        title: "",
        category: { name: "", parentCid: 0, catLevel: 0, showStatus: 1, 
        sort: 0,
        icon: "",
        productUnit : "",
        catId : null,
    },
        dialogVisible : false,
        data: [],
        expandedKey:[],
        defaultProps: {
          children: "children",
          label: "name",
        },
      };
    },
  
    created() {
      this.getMenus();
    },
    mounted() {},
  
    methods: {
        //添加节点
        append(data){
            console.log("append---",data);
            this.dialogType = "add";
            this.title = "添加分类";
            this.category.parentCid = data.catId;
            this.category.catLevel = data.catLevel * 1 + 1;
            this.category.catId = null;
            this.category.name = null;
            this.category.icon = "";
            this.category.productUnit="";
            this.category.sort= 0;
            this.category.showStatus= 1;
            this.dialogVisible = true;

        },

        //上交
        sumitData(){
            if(this.dialogType == "add"){
                this.addCategory();
            }

            if(this.dialogType == "edit"){
                this.editCategory();
            }
        },

        //修改三级分类数据
        editCategory(){
            var { catId, name, icon , productUnit} = this.category;
            this.$http({
                 url: this.$http.adornUrl("/product/category/update"),
                 method: "post",
                 data: this.$http.adornData({catId ,name, icon, productUnit} , false),
      })
        .then(({ data }) => {
            this.$message({
            type: "success",
            message: "菜单修改成功!",
        });
        //关闭对话框
        this.dialogVisible = false;
        //刷新出新的菜单
        this.getMenus();
        this.expandedKey = [this.category.parentCid];
      }).catch(() => {});
        },
        //添加三级分类
         addCategory() {
             console.log("提交的三级分类数据", this.category);
                 this.$http({
                 url: this.$http.adornUrl("/product/category/save"),
                 method: "post",
                 data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "菜单保存成功!",
        });
        //关闭对话框
        this.dialogVisible = false;
        //刷新出新的菜单
        this.getMenus();
        this.expandedKey = [this.category.parentCid];
      }).catch(() => {});
    },

    edit(data){
        console.log("要修改的数据",data);
        this.dialogType = "edit";
        this.title="修改分类";
        //发送请求获取节点最新的数据，数据回显
        this.$http({
            url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
            method:"get",
        }).then((data) => {
            //请求成功
            console.log("要回显得数据",data);
            console.log(data);
            this.category = data.data.category;
            this.dialogVisible = true;
        })


    },



        //删除节点
    remove(node,data){
            console.log("删除节点："+node)
            var ids = [data.catId];
            this.$confirm('是否删除【${data.name}】当前菜单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

            this.$http({
                url: this.$http.adornUrl("/product/category/delete"),
                method:"post",
                data:this.$http.adornData(ids,false),
            }).then(({data}) => {
                this.$message({
                type: 'success',
                message: '菜单删除成功!'
            });
            //刷新出新的菜单
            this.getMenus();
            this.expandedKey=[node.parent.data.catId];
          }).catch(() => {});
        })
            .catch(() => {
            this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },

    //TODO 后续看完视频理解后，再去添加。

    // handleDrop(draggingNode,dropNode,dropType,ev){
    //     console.log("handleDrop:",draggingNode,dropNode,dropType);
    //     //1、当前节点最新父节点id
    //     let pCid = 0;
    //     let siblings = null;
    //     if(dropType = "before")

    // },


      //每次点击的时候
      handleNodeClick(data,node,component) {
        console.log(data,node,component);
        //向父组件发送事件
        //参数1：事件名（自定义命名）
        //后面可以写任意的参数，它们会被传递出去
        this.$emit('tree-node-click', data,node,component);
      },


      //获取所有菜单
      getMenus() {
        this.$http({
          url: this.$http.adornUrl("/product/category/list/tree"),
          methods: "get",
        }).then((data) => {
          console.log("成功获取到菜单信息", data.data.data);
          this.data = data.data.data;
        })
        .catch(() => {});
      },


      //批量保存
      batchSave(){
        this.$http({
            url: this.$http.adornUrl("/product/category/update/sort"),
            methods: "post",
            data:this.$http.adornData(this.updateNodes,false),
        })
            .then(({data}) => {
                this.$message({
                    type:"success",
                    message:"菜单顺序修改成功！"
                });
                //刷新出新的菜单
                this.getMenus();
                //设置需要默认展开的菜单
                this.expandedKey = this.pCid;
                this.updateNodes = [];
                this.maxLevel = 0 ; 
            })

            .catch(() => {});
      },

      //批量删除
      batchDelete() {
                let catIds = [];
                let checkedNodes = this.$refs.menuTree.getCheckedNodes();
                console.log("被选中的元素", checkedNodes);
                for (let i = 0; i < checkedNodes.length; i++) {
                    catIds.push(checkedNodes[i].catId);
                }
                this.$confirm(`是否批量删除【${catIds}】菜单?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                    this.$http({
                        url: this.$http.adornUrl("/product/category/delete"),
                        method: "post",
                        data: this.$http.adornData(catIds, false),
                    })
                        .then(({ data }) => {
                        this.$message({
                            type: "success",
                            message: "菜单批量删除成功!",
                        });
                        // 刷新出新的菜单
                        this.getMenus();
                    })
                        .catch(() => {});
                })
                    .catch(() => {});
            },
    },
  };
  </script>
  
  <style lang="scss">
  .el-tree-node.is-current > .el-tree-node__content {
      background-color: rgb(69, 194, 181) !important;
  }
  </style>